import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class MqttPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MqttPageState();
  }
}

class _MqttPageState extends State<MqttPage> {
  MqttServerClient _mqttClient;
  static String topic = 'android_test';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('mqtt'),
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        OutlineButton(
          child: Text('connect'),
          onPressed: () async {
            _mqttClient = await connect();
          },
        ),
        OutlineButton(
          child: Text('订阅'),
          onPressed: () {
            _mqttClient.subscribe(topic, MqttQos.atLeastOnce);
          },
        ),
        OutlineButton(
          child: Text('消息发布'),
          onPressed: () {
            const pubTopic = 'topic/test';
            final builder = MqttClientPayloadBuilder();
            builder.addString('Hello MQTT');
            _mqttClient.publishMessage(
                pubTopic, MqttQos.atLeastOnce, builder.payload);
          },
        ),
        OutlineButton(
          child: Text('取消订阅'),
          onPressed: () {
            _mqttClient.unsubscribe(topic);
          },
        ),
        OutlineButton(
          child: Text('断开连接'),
          onPressed: () {
            _mqttClient.disconnect();
          },
        ),
      ],
    );
  }

  Future<MqttServerClient> connect() async {
    MqttServerClient client =
        MqttServerClient.withPort('broker.emqx.io', 'flutter_client', 1883);
//    MqttClient mqttClient=MqttClient();
    client.logging(on: true);
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    client.onUnsubscribed = onUnsubscribed;
    client.onSubscribed = onSubscribed;
    client.onSubscribeFail = onSubscribeFail;
    client.pongCallback = pong;

    final connMessage = MqttConnectMessage()
        .authenticateAs('username', 'password')
        .keepAliveFor(60)
        .withWillTopic('willtopic')
        .withWillMessage('Will message')
        .startClean()
        .withWillQos(MqttQos.atLeastOnce);
    client.connectionMessage = connMessage;
    try {
      await client.connect();
      print('mqtt连接: ${client.connectionStatus.state} ');
      client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
        final MqttPublishMessage message = c[0].payload;
        final payload =
            MqttPublishPayload.bytesToStringAsString(message.payload.message);

        print('Received message:$payload from topic: ${c[0].topic}>');
      });
    } catch (e) {
      print('Exception: $e');
      client.disconnect();
    }
    return client;
  }

  // 连接成功
  void onConnected() {
    print('Connected成功');
  }

// 连接断开
  void onDisconnected() {
    print('Disconnected断开连接');
  }

// 订阅主题成功
  void onSubscribed(String topic) {
    print('订阅Subscribed topic: $topic');
  }

// 订阅主题失败
  void onSubscribeFail(String topic) {
    print('订阅失败Failed to subscribe $topic');
  }

// 成功取消订阅
  void onUnsubscribed(String topic) {
    print('取消订阅Unsubscribed topic: $topic');
  }

// 收到 PING 响应
  void pong() {
    print('Ping response client callback invoked');
  }

//  /// Security context
//  SecurityContext context = new SecurityContext()
//    ..useCertificateChain('path/to/my_cert.pem')
//    ..usePrivateKey('path/to/my_key.pem', password: 'key_password')
//    ..setClientAuthorities('path/to/client.crt', password: 'password');
//  client.secure = true;
//  client.securityContext = context;
}
